package com.mason.forum.component;

import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-10-06
 * Time: 18:17
 */
@Component
public class MyThreadPool {

    public static final ExecutorService THREAD_POOL = Executors.newFixedThreadPool(10);

    public static Map<String, Object> submit(FutureTask... tasks) {
        // 提交任务
        for (int i = 0; i < tasks.length; i++) {
            THREAD_POOL.submit(tasks[i]);
        }
        Map<String, Object> map = new HashMap<>();
        // 打包所有任务的返回值
        try {
            for (int i = 1; i <= tasks.length; i++) {
                map.put("task" + i, tasks[i - 1].get());
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        return map;
    }

    public static void submit(Runnable runnable) {
        THREAD_POOL.submit(runnable);
    }

}
